<template >
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片用户列表区域 -->
    <el-card class="box-card">
      <!-- 搜索输入框和添加用户按钮 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input clearable v-model="queryInfo.query" @clear="getUserList('search')" @keyup.enter.native="getUserList('search')" placeholder="请输入内容">
            <el-button @click="getUserList('search')" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="addUserDialog=true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <el-table stripe :data="userList" border style="width: 100%">
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- 获取当前行的所有数据 -->
            <!-- {{scope.row}} -->
            <el-switch v-model="scope.row.mg_state" @change="userChangeState(scope.row)"></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteUserByID(scope.row.id)"></el-button>
            <el-tooltip enterable effect="dark" content="分配角色" placement="top-start">
              <!-- 分配角色按钮 -->
              <el-button @click="assignRole(scope.row)" size="mini" type="warning" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="pageSizes" :page-size="queryInfo.pagesize" :layout="layout" :total="total" background>
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addUserDialog" width="50%" @close="addUserDialogClosed">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input clearable v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input clearable v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input clearable v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input clearable v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialog = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户的对话框 -->
    <el-dialog title="编辑用户" :visible.sync="editUserDialog" width="50%" @close="editUserDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <el-form-item label="用户名">
          <el-input disabled v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input clearable v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input clearable v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialog = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog title="分配用户" :visible.sync="assignRoleDialog" width="50%" @close="assignRoleDialogClosed">
      <div class="assignRole">
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="selectedRole" placeholder="请选择">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="assignRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="assignRoleToUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义邮箱的验证规则
    const checkEmail = (rule, value, callback) => {
      // 邮箱的验证规则
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        // 验证通过
        return callback();
      }
      callback(new Error('请输入正确的邮箱'));
    };

    // 自定义手机号的验证规则
    const checkMobile = (rule, value, callback) => {
      // 手机号的验证规则
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        // 验证通过
        return callback();
      }
      callback(new Error('请输入正确的手机号'));
    };

    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      // 添加用户的form表单数据对象
      addForm: {
        username: 'lkl',
        password: '123456',
        email: 'lkl7956@qq.com',
        mobile: '15981915387'
      },
      // 添加用户的form表单数据验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 12,
            message: '长度在 6 到 12 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 添加用户对话框显示与隐藏的控制值
      addUserDialog: false,
      // 用户信息列表
      userList: [],
      // 用户总数
      total: 0,
      // 分页可供选择的每页显示几条数据
      pageSizes: [1, 2, 3, 5],
      // 分页的功能项
      layout: 'total, sizes, prev, pager, next, jumper',
      // 编辑用户的信息对象
      editForm: {},
      // 编辑用户的信息验证规则对象
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 编辑用户对话框显示隐藏控制值
      editUserDialog: false,
      // 分配角色对话框显示隐藏控制值
      assignRoleDialog: false,
      // 点击分配角色按钮当前角色的信息
      userInfo: {},
      // 所有角色数据数组
      rolesList: [],
      // 被选中的角色id
      selectedRole: ''
    }
  },
  methods: {
    // 获取用户数据列表的事件函数
    async getUserList(keywords) {
      if (keywords === 'search') {
        this.queryInfo.pagenum = 1;
        this.queryInfo.pagesize = 2;
      }
      const res = await this.$axios.get('users', { params: this.queryInfo });
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败');
      this.userList = res.data.users;
      this.total = res.data.total;
      // console.log(this.userList);
    },

    // 关闭添加用户对话框的重置表单事件函数
    addUserDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },

    // 添加用户的点击事件函数
    addUser() {
      // 提交表单数据预验证
      this.$refs.addFormRef.validate(async valid => {
        // console.log(valid);
        if (!valid) return;
        // 验证数据通过，发起请求
        const res = await this.$axios.post('users', this.addForm);
        // console.log(res);
        if (res.meta.status !== 201) return this.$message.error('添加用户失败！');
        this.$message.success('添加用户成功！');
        // 关闭对话框
        this.addUserDialog = false;
        // 刷新用户数据表格
        this.getUserList();
      });
    },

    // 分页区域pageSize 改变时触发的事件
    handleSizeChange(newSize) {
      // console.log(newSize);
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },

    // 分页区域currentPage 改变时触发的事件
    handleCurrentChange(newPage) {
      // console.log(current);
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },

    // 修改用户状态的事件函数
    async userChangeState(userInfo) {
      // console.log(userInfo);
      const res = await this.$axios.put(`users/${userInfo.id}/state/${userInfo.mg_state}`);
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error('用户状态更新失败！');
      }
      this.$message.success('用户状态更新成功！');
    },

    // 显示修改用户的对话框，并修改用户信息
    async showEditDialog(id) {
      console.log(id);
      this.editUserDialog = true;
      // 根据id获取用户信息并赋值给data中的editForm对象
      const res = await this.$axios.get('users/' + id);
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error('获取用户信息失败！');
      this.editForm = res.data;
    },

    // 重置修改用户表单
    editUserDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },

    // 修改用户信息
    editUserInfo() {
      // 对表单数据预验证
      // 提交表单数据预验证
      this.$refs.editFormRef.validate(async valid => {
        // console.log(valid);
        if (!valid) return;
        // 验证数据通过，发起请求
        const res = await this.$axios.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        });
        // console.log(res);
        if (res.meta.status !== 200) return this.$message.error('编辑用户失败！');
        this.$message.success('编辑用户成功！');
        // 关闭对话框
        this.editUserDialog = false;
        // 刷新用户数据表格
        this.getUserList();
      });
    },

    // 弹出删除信息框
    async deleteUserByID(id) {
      // 弹出信息提示框并通过async/await 简化异步事件操作
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);

      // console.log(confirmResult);
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除操作！');
      const res = await this.$axios.delete('users/' + id);
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error('删除用户失败！');
      this.$message.success('删除用户成功！');
      // 为了在删除最后一页的最后一条数据时能成功跳转回最后一页的上一页
      const totalPage = Math.ceil((this.total - 1) / this.queryInfo.pagesize) // 总页数
      this.queryInfo.pagenum = this.queryInfo.pagenum > totalPage ? totalPage : this.queryInfo.pagenum;
      this.queryInfo.pagenum = this.queryInfo.pagenum < 1 ? 1 : this.queryInfo.pagenum;
      // 刷新用户数据列表
      this.getUserList();
    },

    // 监听分配角色对话框关闭时间，重置信息
    assignRoleDialogClosed() {
      this.selectedRole = '';
      this.userInfo = {};
    },

    // 分配角色按钮点击事件
    async assignRole(userInfo) {
      // console.log(userInfo);
      // 显示对话框
      this.assignRoleDialog = true;
      // 把当前用户信息赋值非userInfo对象
      this.userInfo = userInfo;
      // 调接口获取所有角色列表
      const res = await this.$axios.get('roles');
      if (res.meta.status !== 200) return this.$message.error('获取角色列表数据失败！');
      this.rolesList = res.data;
    },

    // 发请求分配用户角色
    async assignRoleToUser() {
      if (!this.selectedRole) return this.$message.error('请选择要分配的角色！');
      const res = await this.$axios.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRole });
      if (res.meta.status !== 200) return this.$message.error('更换角色失败！');
      this.$message.success('更换角色成功！');
      // 关闭对话框
      this.assignRoleDialog = false;
      // 重新渲染用户数据
      this.getUserList();
    }
  },

  // 在生命周期虚拟DOM元素创建完成后调用获取数据的请求函数
  created() {
    this.getUserList();
  }
}
</script>

<style lang="less" scoped>
.assignRole p {
  margin: 15px 0;
}
</style>
